﻿using Iworld.Administrator.Model;
using Iworld.basis.Service;
using Iworld.Basis.Help;
using Iworld.Basis.Manager;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;

namespace Iworld.Administrator.Service.Import
{

     [DataContract]
  public  class EditAdministratorImport : CheckAdministratorImportBase, IPackageForUpdateModel<IModelToDbContextOfAdministrator,
         Iworld.Administrator.Model.Administrator>
    {
       
      [DataMember]
      public int Id
      {
          set;
          get;
      }

      /// <summary>
      /// 账号
      /// </summary>
      [DataMember]
      public string Account { get; set; }

      /// <summary>
      /// 用户名
      /// </summary>
      [DataMember]
      public string Username { get; set; }

      /// <summary>
      /// 新的密码
      /// </summary>
      [DataMember]
      public string NewPassword { get; set; }

      /// <summary>
      /// 所从属的管理员组的存储指针
      /// </summary>
      [DataMember]
      public int GroupId { get; set; }

      AdministratorGroup group ;

      public override void CheckAllowExecuteOrNot(Main.Impl.ModelToDbContext db)
      {
          base.CheckAllowExecuteOrNot(db);
          if (!Self.Group.CanEditAdministrator)
          {
              throw new Exception("你无权修改或添加管理员");
          }

      }

        public void CheckData(IModelToDbContextOfAdministrator db)
        {
            if (SuperAcountInfoPackage.Account ==  db.Administrators.Find(this.Id).Account)
            {
                throw new Exception("不能修改超级管理员");
            }
            this.Account = VerifyHelper.EliminateSpaces(this.Account);
            this.NewPassword = VerifyHelper.EliminateSpaces(this.NewPassword);
            VerifyHelper.Check(this.Account, VerifyHelper.Key.Nickname);
            if (!string.IsNullOrWhiteSpace(NewPassword))
            {
               VerifyHelper.Check(this.NewPassword, VerifyHelper.Key.Password);
            }
            bool hadUsedUsername = db.Administrators.Any(x => x.Account == this.Account && x.Id != this.Id);
            if (hadUsedUsername)
            {
                string error = string.Format("账号 {0} 已经被使用", this.Account);
                throw new Exception(error);
            }
            group = db.AdministratorGroups.Find(this.GroupId);
            if (group == null) throw new Exception("管理员组不存在");
        }

        public void Update(Model.Administrator model)
        {
            model.Account = this.Account; 
            model.Username = this.Username;
            if (!string.IsNullOrWhiteSpace(NewPassword))
            {
                string password = EncryptHelper.EncryptByMd5(this.NewPassword);
                model.Password = password;
            }
            model.Group = group;
        }
    }
}
